//
//  RHBaseWebViewController.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/7/6.
//

#import "RHBaseWebViewController.h"
#import <WebKit/WebKit.h>
#import "JsDataModel.h"

@interface RHBaseWebViewController ()<WKNavigationDelegate, WKUIDelegate, UINavigationControllerDelegate>


@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) CALayer *progresslayer;

@property (nonatomic, strong) UIBarButtonItem *leftBarBtn;

@end

@implementation RHBaseWebViewController

- (void)setUrlStr:(NSString *)urlStr{
    _urlStr = urlStr;
    //中文编码
    NSString * encodingString = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                                    (CFStringRef)urlStr,
                                                                                                    (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                                                                                    NULL,
                                                                                                    kCFStringEncodingUTF8));
    _urlStr = encodedString;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.navigationItem.title = _navTitle;
    _isDynamicTitle = YES;
    [self setupUI];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)setupUI{
    
    [self.view setBackgroundColor:[UIColor colorWithHexString:@"#f2f3f5"]];
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,40, 44)];
    [backButton setImage:[UIImage imageNamed:@"back_icon"] forState:UIControlStateNormal];
    [backButton setTitle:@"" forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [backButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 11, 0, 0)];
    [backButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [backButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    _leftBarBtn = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    spaceItem.width = -2;
    
    if ([self.navigationController.viewControllers indexOfObject:self]!=0) {
        self.navigationItem.leftBarButtonItems = @[spaceItem,_leftBarBtn];
    }else{
        self.navigationItem.leftBarButtonItems = @[];
    }
    
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
    
    //    Weakself;
    //    CLNavigationController *nav = (CLNavigationController*)self.navigationController;
    //    nav.backActionBlock = ^{
    //        [weakSelf backAction];
    //    };
    
    //self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0,kNavBarHeight, kUI_WINDOW_W, kUI_WINDOW_H-kNavBarHeight)];
    self.webView.backgroundColor = [UIColor clearColor];
    [self.webView.scrollView setBackgroundColor:[UIColor clearColor]];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    self.webView.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_webView];
    
    kWeakSelf;
    _webView.scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf pullRefresh];
    }];
    
    [_webView.scrollView.mj_header setHidden:YES];
    
    [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    //监听Web--》Title
    //  [_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    
    _progress = [[UIView alloc] initWithFrame:CGRectMake(0,0, 0, 1)];
    _progress.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_progress];
    
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(0);
        make.left.mas_offset(0);
        make.bottom.mas_offset(0);
        make.right.mas_offset(0);
    }];
    
    [_progress mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.webView).offset(0);
        make.size.mas_equalTo(CGSizeMake(0, 1));
        make.left.equalTo(weakSelf.webView);
    }];
    
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(0, 0, 0, 1);
    layer.backgroundColor = [UIColor colorWithHexString:@"#3ECE80"].CGColor;
    [_progress.layer addSublayer:layer];
    self.progresslayer = layer;
    
    if(self.localHtml.length>0){
        NSString *filePath = [[NSBundle mainBundle]pathForResource:self.localHtml ofType:@"html"];
        NSURL *url = [NSURL fileURLWithPath:filePath];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [self.webView loadRequest:request];
        
    }
    
    if(self.urlStr.length>0){
        NSURL *url = [NSURL URLWithString:self.urlStr];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [self.webView loadRequest:request];
        
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    //[self.webView removeObserver:self forKeyPath:@"title"];
    
    NSArray * types = @[WKWebsiteDataTypeMemoryCache, WKWebsiteDataTypeDiskCache];
    NSSet *websiteDataTypes = [NSSet setWithArray:types];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{}];
    
}

- (void)beginInToPage{
    
}

- (void)endGoOutPage{
    
}

#pragma mark - upDate
- (void)pullRefresh{
    ReachabilityStatus status = [GLobalRealReachability currentReachabilityStatus];
    if (status != RealStatusNotReachable) {
        NSURL *url = _webView.backForwardList.currentItem.URL?_webView.backForwardList.currentItem.URL:[NSURL URLWithString:self.urlStr];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [_webView loadRequest:request];
    }else{
        [_webView.scrollView.mj_header endRefreshing];
        [SVProgressHUD showErrorWithStatus:@"network error"];
    }
}


#pragma mark - Action  Method
- (void)backAction{
    if ([self.webView canGoBack]) {
        _backNavigation = [self.webView goBack];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
        
    }
    //调用 iOS->Js
    //    [self.bridge callHandler:@"getDateFromJs" data:@{@"iOS": @"test"} responseCallback:^(id responseData) {
    //        NSLog(@"from js: %@", responseData);
    //    }];
}

//Web跳转
- (void)jumpToController:(JsDataModel *)model{
    
    if ([model.type isEqualToString:@""]) {
        //详情页立即申请
    }
    
    if ([model.type isEqualToString:@""]) {
        //首页h5页其他跳转
        
    }
    
    if ([model.type isEqualToString:@""]) {
        //返回首页
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    
    if ([model.type isEqualToString:@""]) {
        //点击事件统计
    }
}

#pragma mark -- 实现监听方法

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        
        self.progresslayer.opacity = 1;
        //不要让进度条倒着走...有时候goback会出现这种情况
        if ([change[@"new"] floatValue] < [change[@"old"] floatValue]) {
            return;
        }
        self.progresslayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[@"new"] floatValue], 3);
        if ([change[@"new"] floatValue] == 1) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progresslayer.opacity = 0;
            });
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progresslayer.frame = CGRectMake(0, 0, 0, 3);
            });
        }
        
    }else if ([keyPath isEqualToString:@"title"]){
        
        if (object == self.webView) {
            NSString *str = self.tabBarItem.title;
            if (_isDynamicTitle) {
                self.title = self.webView.title;
            }
            self.tabBarItem.title = str;
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark -- WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
    //[SVProgressHUD showInfoWithStatus:nil];
    
    NSLog(@"页面开始加载时调用");
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation{
    NSLog(@"当内容开始返回时调用");
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    [_webView.scrollView.mj_header endRefreshing];
    if ([_backNavigation isEqual:navigation]) {
        // 这次的加载是点击返回产生的，刷新
        [webView reload];
        _backNavigation = nil;
    }
    //[SVProgressHUD dismiss];
}

//提交发生错误时调用
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"提交发生错误时调用");
    [_webView.scrollView.mj_header endRefreshing];
    //[SVProgressHUD dismiss];
    
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    //[SVProgressHUD dismiss];
    [_webView.scrollView.mj_header endRefreshing];
    ReachabilityStatus status = [GLobalRealReachability currentReachabilityStatus];
    if (status == RealStatusNotReachable) {
        
        [[AFNetworkReachabilityManager sharedManager] startMonitoring];
        [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            if (status == AFNetworkReachabilityStatusNotReachable || status == AFNetworkReachabilityStatusUnknown) {
                //无网络链接
            } else {
                //网络链接成功
                NSURL *url = webView.backForwardList.currentItem.URL?webView.backForwardList.currentItem.URL:[NSURL URLWithString:self.urlStr];
                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
                [webView loadRequest:request];
            }
        }];
    }else{
        
        NSLog(@"error debugDescription ==== %@",[error debugDescription]);
        if (![error.userInfo[@"NSErrorFailingURLStringKey"] containsString:@"https://item.m.jd.com/product/"]) {
            [SVProgressHUD showErrorWithStatus:@"Server access failed. Please try again later"];
        }
        
    }
    
    NSLog(@"页面加载失败时调用");
    [_webView.scrollView.mj_header endRefreshing];
}

// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
    NSLog(@"接收到服务器跳转请求之后调用");
}

// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    NSLog(@"url_end:%@",navigationResponse.response.URL.absoluteString);
    [webView setNeedsLayout];
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}

//在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSLog(@"url_begin:%@",navigationAction.request.URL.absoluteString);
    NSURL *URL = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    if ([scheme isEqualToString:@"tel"]) {
        NSString *resourceSpecifier = [URL resourceSpecifier];
        NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", resourceSpecifier];
        /// 防止iOS 10及其之后，拨打电话系统弹出框延迟出现
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
        });
        
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationActionPolicyCancel);
}

//需要响应身份验证时调用 同样在block中需要传入用户身份凭证
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
    //用户身份信息
    /*NSURLCredential * newCred = [[NSURLCredential alloc] initWithUser:@"user123" password:@"123" persistence:NSURLCredentialPersistenceNone];
     //为 challenge 的发送方提供 credential
     [challenge.sender useCredential:newCred forAuthenticationChallenge:challenge];
     completionHandler(NSURLSessionAuthChallengeUseCredential,newCred);*/
    
    //    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
    //        if ([challenge previousFailureCount] == 0) {
    //            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
    //            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
    //        } else {
    //            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    //        }
    //    } else {
    //        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    //    }
    
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        NSURLCredential *card = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
        completionHandler(NSURLSessionAuthChallengeUseCredential, card);
    }
}

//进程被终止时调用
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView API_AVAILABLE(macosx(10.11), ios(9.0)){
    NSLog(@"进程被终止时调用");
    //[SVProgressHUD dismiss];
    [_webView.scrollView.mj_header endRefreshing];
}


#pragma mark - WKUIDelegate
// 页面是弹出窗口 _blank 处理
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

// 输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消".rh_localized style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
}
// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    NSLog(@"%@",message);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"HTML的弹出框" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
